var express = require('express');
var router = express.Router();
let { clientmodel,Login } = require('../db/model')
let { StringDecoder } = require("string_decoder")
let multiparty = require('multiparty')
let fs = require('fs')
let { randomCode, sendCode } = require('./code')
const jwt=require('jsonwebtoken')
const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const AlipaySdk = require('alipay-sdk').default
const AlipayFormData = require('alipay-sdk/lib/form').default
const alipaySdk = new AlipaySdk({
    appId: '9021000138621360',
    signType: "RSA2",
    gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do",
    alipayPublicKey: 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp8xbY1EPo0AzqptLcYI6Yt26fxdBEolDT/p7yrc9y05tWBOmpJx+L2qDjvQ+iGsKXQACXQ0ROj9+ZwoJCgUtyJk7vxSFkg0yj9cx4LSb+i/aVm+ccsasXYr/Ih4C6FYsb0YRJOz64yAN36XC/krXsPloTfaxZFNuUqc203mxy2wwwrlgh6LEPlmpG+e0FFRF7Wc5L4uZn5g9cggK6wGxDwYVqOhm3ZWLqeTd1dOcQIjRx4CKDa7WzGJaMpwqBiW+HkO325FAdcLlzw0yOyKflQHIhwSXHGt/59c500/zcsYCsKv14CqVP7xjql/TO0/Bfem3SVfvR/k4iCTh69bD0QIDAQAB',
    privateKey: 'MIIEogIBAAKCAQEAyUK9f2B9x6B29thQQzEhN1NbB9f2Cqk+cM9res0AXgxptCxF5yVeeAC9vtYnGh0MyWE8/pkweRAFvQ7CxvqHLV4ZCh2zqrrRrIZnipPaU+gTRN32VZVujMgYnsJJSZNqCBey8/oXp9hSbQo4bWgL0K+fFXDK2GVRrDelXzzsdF5nWVPllRcYBOn0dQVruTklpDmefQYD1IrOK/ATx+GEwxyo30HkkTEfe0hEZ7U2I9R/qlpPJEcuHDr3QIr7fBXaKBNvRK99hp/16ffmH0DDeXqTvuESXx4geqMHKIeUekcnLvDED6luqblra70lztqA/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mRy+QkdAtAoGAGMEC97nOzoQFS3vh1SBQYk9cMdsemHHSCuP3AhiccsnU0pkVwTrEntDk2dh9dXh94SDgrgR8Y+XZGxVUcJKDjAKFa9zHnFmxi6yR7AmC0c4ZVXSYf1TSEIxK3cOkmiN2JBcdR47Ya9FAq9KTbQuy0D2/wQhBlDnLj1xRKD+VzVo='
})
router.post('/adduser', async (req, res) => {
    let { uname, pwd, phoneid } = req.body
    console.log(uname);

    let idx = await clientmodel.findOne({ uname, pwd, phoneid })
    console.log(idx);
    if (idx) {
        res.send({
            code: 200
        })
    } else {
        clientmodel.create({ uname, pwd, phoneid })
        res.send({
            code: 200,
            msg: '注册成功’'
        })
    }
})
// 手机号修改
router.post('/editpid', async (req, res) => {
    // 从请求体中提取 phoneid
    let { oldp, newp } = req.body
    // let phoneid = Number(req.body.phoneid);
    console.log(oldp, 'oldp', newp, 'newp');
    // 检查 phoneid 是否为有效数字
    if (isNaN(oldp)) {
        return res.status(400).send({
            code: 400,
            msg: 'phoneid 不是有效的数字'
        });
    }
    try {
        // 查找 clientmodel 中的记录
        let idx = await clientmodel.findOne({ phoneid: oldp });
        console.log(idx, '7896');

        if (idx) {
            await clientmodel.updateOne({ phoneid: oldp }, { phoneid: newp });
            res.send({
                code: 200,
                msg: '手机号修改成功'
            });
        } else {
            res.send({
                code: 201,
                msg: '请先注册，该手机号不存在'
            });
        }
    } catch (error) {
        // 错误处理
        console.error('查询出错:', error);
        res.status(500).send({
            code: 500,
            msg: '服务器内部错误'
        });
    }
});
// 获取验证码
// 验证码
router.post('/getcode', (req, res) => {
    let { phoneid } = req.body
    console.log(phoneid);

    let code = randomCode(4)  //生成四位随机验证码
    sendCode(phoneid, code, function (success) {
        if (success) {
            res.send({
                code: 200,
                msg: '短信验证码发送成功',
                data: code
            })
        } else {
            res.send({
                code: 200,
                msg: '短信验证码发送失败',
                data: code
            })
        }
    })
})
// 设置登录密码
router.post('/setpwd', async (req, res) => {
    let { phoneid, pwd } = req.body
    console.log(phoneid, pwd);

    let idx = await clientmodel.findOne({ phoneid })
    console.log(phoneid);

    if (idx) {
        await clientmodel.updateOne({ phoneid }, { pwd: req.body.pwd })
        res.send({
            code: 200,
            msg: '设置成功'
        })
    } else {
        res.send({
            code: 201,
            msg: '设置失败'
        })

    }
})
router.post('/login', async (req, res) => {
    const data = await Login.findOne({ phone: req.body.tel, password: req.body.pwd })
    if (data) {
        console.log(data);
        const token = ' Bearer  ' + jwt.sign({ id: data._id }, '123456', { expiresIn: '1h' })
        res.send({
            code: 200,
            msg: '登录成功',
            token,
            phone:data.phone
        })
    } else {
        res.send({
            code: 400,
            msg: '登录失败'
        })
    }
})
let yanzhengma = ''
// 生成随机验证码
function generateCode() {
    const code = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
    // yanzhengma = code.toString()
    return code.toString();
}
router.post('/sendyzm', async (req, res) => {
    let code = generateCode()
    yanzhengma = code
    class Client {
        static createClient() {
            let config = new OpenApi.Config({
                accessKeyId: 'LTAI5t9WnHjntoHRkgwQFYv4',
                accessKeySecret: 'zHbwcx5qknexgZNcQuFtieC9kQjIkm',
            });
            config.endpoint = `dysmsapi.aliyuncs.com`;
            return new Dysmsapi20170525.default(config);
        }
        static async main(args) {
            let client = Client.createClient();
            let sendSmsRequest = new Dysmsapi20170525.SendSmsRequest({
                signName: '心理健康咨询预约培训客户',
                templateCode: 'SMS_468900207',
                phoneNumbers: req.body.phone,
                templateParam: JSON.stringify({
                    "code": code
                })
            });
            console.log(sendSmsRequest)
            let runtime = new Util.RuntimeOptions({});
            try {
                // 复制代码运行请自行打印 API 的返回值
                await client.sendSmsWithOptions(sendSmsRequest, runtime);
            } catch (error) {
                // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
                // 错误 message
                console.log(error.message);
                // 诊断地址
                // console.log(error.data["Recommend"]);
                Util.default.assertAsString(error.message);
            }
        }

    }
    exports.Client = Client;
    Client.main(process.argv.slice(2));
    res.send({
        code: 200,
        msg: '发送成功'
    })

})
router.post('/yzmlogin', async (req, res) => {
    const data = await Login.findOne({ phone: req.body.tel })
    if (req.body.yzm === yanzhengma) {
        const token = ' Bearer  ' + jwt.sign({ id: data._id }, '123456', { expiresIn: '1h' })
        res.send({
            code: 200,
            msg: '验证码正确',
            token
        })
    } else {
        res.send({
            code: 400,
            msg: '验证码错误'
        })
    }
})
router.put('/edit', async (req, res) => {
    if (req.body.yzm === yanzhengma) {
        await Login.findOneAndUpdate({ phone: req.body.tel }, {
            password: req.body.pwd
        })
        res.send({
            code: 200,
            msg: '修改成功'
        })
    } else {
        res.send({
            code: 400,
            msg: '验证码错误'
        })
    }
})
router.post("/pcpay", async (req, res) => {
    const formData = new AlipayFormData()
    formData.setMethod('get');
    // 通过addField增加参数
    // 在用户支付完成之后，支付宝服务器会根据传入的notify_url,以post请求的形式将支付结果作为参数通知到商户系统
    // 支付成功或失败都返回
    formData.addField('returnUrl', "http://localhost:5173/app");
    formData.addField('bizContent', {
        out_trade_no: Date.now().toString(36),//订单号 64个字符以内 可包含字母、数字、下划线、且不能重复
        product_code: "FAST_INSTANT_TRADE_PAY",//销售产品码，与支付宝签约的产品码名称，仅支持FAST_INSTANT_TRADE_PAY
        total_amount: req.body.price,// 订单总金额
        subject: '1221',// 订单描述
        body: '34234',// 商品描述
    })
    // 返回promise
    const result = await alipaySdk.exec(
        'alipay.trade.wap.pay',//统一收单下单并支付页面接口,
        {},//api请求的参数（包含 “公共请求参数”和“业务参数”）
        { formData: formData }// result为可以跳转支付链接的url
    )
    // res.json({ url: result })
    res.send({
        code: 200,
        result
    })
})
module.exports = router;
